package org.test.client.ui.left;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.JComponent;

import org.test.client.ui.util.UIUtil;
import org.test.client.ui.util.run.ExpandCompRun;

/**
 * @author Guodeqi
 *
 */
public class leftMenu extends JComponent{
	private LeftMenuBar parentMBar;
	
	private leftMenu thisMenu = this;
	
	private LeftMenuItem items = null;
	private Vector<LeftMenuItem> childs	=null;
	
	private int ww = 0;
	private int hh = 0;
	private int nowhh = 0;
	
	private boolean closed = LeftMenuBar.closedChildItem;

	public leftMenu(LeftMenuItem items){
		this.items = items;
		ww = items.getDefaultw();
		childs = items.getChilds();
		
		hh = items.getDefaulth()+childs.size()*items.getDefaulth();
		nowhh = items.getDefaulth();
		
		this.setLayout(new FlowLayout(FlowLayout.RIGHT, 0, 0));
		Dimension d = items.getPreferredSize();
		if(closed){
			this.setPreferredSize(new Dimension(d.width,d.height));
		}else{
			this.setPreferredSize(new Dimension(d.width,d.height*(1+childs.size())));
		}
		
		doInit();
	}
	
	@Override
	public Insets getInsets() {
		return new Insets(0, 0, 0, 0);
	}
	
	public void doInit() {
		
		this.add(items);
		int size = childs.size();
		for (int i = 0; i < size; i++) {
			LeftMenuItem leftMenuItem = childs.get(i);
			if(leftMenuItem.getChilds().size() == 0){
				this.add(leftMenuItem);
				leftMenuItem.changeClickUI = false;
			}else{
				//暂时只考虑 2级菜单
//				this.add(new leftMenu(leftMenuItem));
			}
		}
		
		items.isSingleItem = true;
		items.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent mouseevent) {
				if(closed){
					thisMenu.setClosed(false);
				}else{
					thisMenu.setClosed(true);
				}
			}
		});
	}

	@Override
	public void paintComponents(Graphics g) {
		super.paintComponents(g);
		this.setBackground(this.getParent().getBackground());
		
		Graphics2D g2d = (Graphics2D)g;
		UIUtil.setAntiAliasing(g2d, true);

		g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
		g2d.setColor(items.lineColor);
		g2d.drawLine(0, 0, ww, 0);
		g2d.drawLine(0, nowhh-1, ww, nowhh-1);
	}
	
	
	public boolean getClosed() {
		return closed;
	}

	public void setClosed(boolean closed) {
		if(closed != this.closed){
			this.closed = closed;
			int changeHeight = hh - nowhh;
			if(changeHeight == 0){
				return ;
			}
			ExpandCompRun run = new  ExpandCompRun(thisMenu, !closed, changeHeight);
			new Thread(run).start();
		}
	}

	public void setMenuBar(LeftMenuBar mbar){
		this.parentMBar = mbar;
	}
	
}
